package com.ukao.cashregister.ui.stokin;


import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.ukao.cashregister.R;
import com.ukao.cashregister.adapter.PayTagAdapter;
import com.ukao.cashregister.base.BaseFragment;
import com.ukao.cashregister.bean.BalanceBean;
import com.ukao.cashregister.bean.PayInfoBean;
import com.ukao.cashregister.consts.Constant;
import com.ukao.cashregister.consts.SaveParamets;
import com.ukao.cashregister.eventbus.PayAmountEvent;
import com.ukao.cashregister.eventbus.PayEvent;
import com.ukao.cashregister.retrofit.ApiCallback;
import com.ukao.cashregister.utils.CheckUtils;
import com.ukao.cashregister.utils.DecimalUtil;
import com.ukao.cashregister.utils.KeyBoardUtil;
import com.ukao.cashregister.utils.L;
import com.ukao.cashregister.utils.T;
import com.ukao.cashregister.utils.Utils;
import com.ukao.cashregister.widget.StateButton;
import com.ukao.cashregister.widget.TagFlowLayout;

import org.greenrobot.eventbus.Subscribe;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import rx.Observable;

import static com.ukao.cashregister.eventbus.PayEvent.Message.PAY_SUCCEED;

/**
 * 银联支付
 */
public class UnionpayFragment extends BaseFragment {

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.remark)
    EditText remark;
    @BindView(R.id.sure_gather)
    StateButton sureGather;
    Unbinder unbinder;
    @BindView(R.id.should_Price)
    TextView shouldPrice;
    @BindView(R.id.id_tagflowlayout)
    TagFlowLayout idTagflowlayout;

    private String orderId;
    private String shouldPice = "0";
    private String balance;
    private PayInfoBean mPayInfo;
    private String userId;
    private String rechargeAmount;

    private String withActive;
    private PayTagAdapter mPayTagAdapter;
    public String paySign;
    public static UnionpayFragment newInstance(String param1, String param2, String rechargeAmount, String withActive) {
        UnionpayFragment fragment = new UnionpayFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        args.putString(ARG_PARAM3, rechargeAmount);
        args.putString(ARG_PARAM4, withActive);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            orderId = getArguments().getString(ARG_PARAM1);
            userId = getArguments().getString(ARG_PARAM2);
            rechargeAmount = getArguments().getString(ARG_PARAM3);
            withActive = getArguments().getString(ARG_PARAM4);
            if (!CheckUtils.isEmpty(rechargeAmount)) {
                shouldPice = rechargeAmount;

            }
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_unionpay, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        return view;
    }

    @Override
    protected void initView() {
        showGathering();
    }


    public void showGathering() {

        if (shouldPice.indexOf(".") != -1) {
            Spannable span = new SpannableString(shouldPice);
            span.setSpan(new AbsoluteSizeSpan(CheckUtils.isMIUIDevices() ? 45 : 60), shouldPice.indexOf("."), shouldPice.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            shouldPrice.setText(span);
        } else {
            shouldPrice.setText(shouldPice);
        }


    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(PayAmountEvent event) {
        switch (event.getMessage()) {
            case otherRecharge:
                PayInfoBean  mPayInfos = (PayInfoBean) event.getData();
                fillpaySignData(mPayInfos);
                break;

            case PAY_COUNT:  //获得支付信息
                mPayInfo = (PayInfoBean) event.getData();
                fillpaySignData(mPayInfo);
                balance = mPayInfo.getPayBalance() + "";
                shouldPice = CheckUtils.isEmptyNumber(mPayInfo.getShouldPrice());
                showGathering();

                break;

            case recharge: /*充值信息*/
                HashMap mHashMap = (HashMap) event.getData();
                rechargeAmount = (String) mHashMap.get(ARG_PARAM1);
                withActive = (String) mHashMap.get(ARG_PARAM2);
                shouldPice = rechargeAmount;
                showGathering();

                break;


        }
    }


    @OnClick(R.id.sure_gather)
    public void onViewClicked() {
        if (!CheckUtils.isEmpty(userId)||mPayInfo!=null){
            KeyBoardUtil.hideInputmethod(remark);
            unionPay();
        }


    }

    /**
     * 填充银行卡标签
     * @param mPayInfo
     */

    public  void  fillpaySignData(PayInfoBean  mPayInfo){
        if (mPayInfo!=null&&mPayInfo.isEnableOther()&&mPayTagAdapter==null){
            mPayTagAdapter= new PayTagAdapter(activity, mPayInfo.getPaySignList());
            idTagflowlayout.setAdapter(mPayTagAdapter);
        }
    }

    public void unionPay() {
        showProgressDialog();
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParamets.getToken(Utils.getContext()));
        Observable observable = null;
        paySign="";
        if (mPayTagAdapter!=null&&mPayTagAdapter.getCount()!=0){
            int selectPos =-1;
            for (Integer pos : idTagflowlayout.getSelectedList()) {
                selectPos =pos;
            }
            if (selectPos !=-1){
                PayInfoBean.PaySignListBean mItem = mPayTagAdapter.getItem(selectPos);
                paySign= mItem.getVal();
            }
        }

        if (!CheckUtils.isEmpty(userId)) {  /*充值*/
            mHashMap.put("withActive", withActive);
            mHashMap.put("userId", userId);
            if (!CheckUtils.isEmpty(paySign)){  /*银行卡选项*/
                mHashMap.put("paySign", paySign);
            }
            mHashMap.put("remark", getText(remark));
            mHashMap.put("amount", DecimalUtil.multiply(rechargeAmount));
            //withActive 是否参与充值活动(非必传，默认参与)
                observable = apiStores().otherRecharge(Constant.createParameter(mHashMap));
        } else {
            mHashMap.put("orderId", orderId);
            mHashMap.put("remark", getText(remark)); //输入的备注
            if (!CheckUtils.isEmpty(mPayInfo.getCpnRelId())) {  /*优惠券id*/
                mHashMap.put("cpnRelId", mPayInfo.getCpnRelId());
            }
            if (!CheckUtils.isEmpty(paySign)){  /*银行卡选项*/
                mHashMap.put("paySign", paySign);
            }
            if (mPayInfo.isUseUPay()) {
                mHashMap.put("groupCardType", "41");//groupCardType 支付(团)卡类型 41-优付卡
            } else {
                mHashMap.put("balance", balance);
            }
            observable = apiStores().otherPay(Constant.createParameter(mHashMap));
        }

        L.i("mHashMap=" + mHashMap.toString());
        addSubscription(observable,
                new ApiCallback<BalanceBean>() {
                    @Override
                    public void onSuccess(BalanceBean model) {
                        if (model.getHttpCode() == 200) {
                            PayEvent.postNoData(PAY_SUCCEED);
                        } else {
                            T.show(model.getMsg());
                        }

                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }

                });
    }





}
